package com.fanben100.biz;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Properties;

import javax.swing.JOptionPane;

import com.fanben100.constant.SystemConstant;
import com.fanben100.domain.SysConfig;
import com.fanben100.exception.LoadConfigException;

/**
 * 外部properties文件配置读取策略
 * 
 * @author Administrator
 * 
 */
public class OuterPropertyStrategy extends PropertyStrategy {

	@Override
	public void algorithmInterface(String... fileName)
			throws LoadConfigException {
		String filePath = getJarDir() + "/config/"
				+ SystemConstant.UI_CONFIG_PATH;
		InputStream in = null;
		try {
			in = new BufferedInputStream(new FileInputStream(filePath));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
			JOptionPane.showMessageDialog(null, e1.getMessage());
			throw new LoadConfigException("无法找到配置资源", e1);
		}
		if (in != null) {
			Properties p = new Properties();
			try {
				p.load(in);
			} catch (IOException e) {
				JOptionPane.showMessageDialog(null, e.getMessage());
				e.printStackTrace();
			}
			if (p != null) {
				try {
					SysConfig.sellerId = Integer.valueOf(p
							.getProperty(SystemConstant.SELLER_ID_KEY));
					SysConfig.sellerName = p
							.getProperty(SystemConstant.SELLER_NAME_KEY);
					SysConfig.loaded = true;
				} catch (NumberFormatException nfe) {
				}
			}
		}
	}

	public static String getJarDir() {
		String path = getDirFromClassLoader();
		if (path == null) {
			path = System.getProperty("user.dir");
		}
		return path;
	}

	/**
	 * 从通过Class Loading计算路径： 1 class文件通过jar包加载： 如果为jar包，该包为d:/test/myProj.jar
	 * 该方法返回d:/test这个目录（不受用户工作目录影响） 提示：在jar包加载
	 * 的时候，通过指定加载OuterPropertyStrategy的class资源得到jar:<url>!/{entry}计算出加载路径 2
	 * class文件直接被加载：
	 * 如果是web工程,class文件放在D:\tools\apache-tomcat-5.5.27\webapps\webProj
	 * \WEB-INF\classes
	 * 该方法返回D:\tools\apache-tomcat-5.5.27\webapps\webProj\WEB-INF
	 * 即返回放class文件夹的上一层目录。
	 * */
	private static String getDirFromClassLoader() {
		try {
			String path = OuterPropertyStrategy.class.getName().replace(".",
					"/");
			path = "/" + path + ".class";
			URL url = OuterPropertyStrategy.class.getResource(path);
			String jarUrl = url.getPath();
			if (jarUrl.startsWith("file:")) {
				if (jarUrl.length() > 5) {
					jarUrl = jarUrl.substring(5);
				}
				jarUrl = jarUrl.split("!")[0];

			} else {
				jarUrl = OuterPropertyStrategy.class.getResource("/")
						.toString().substring(5);
			}
			File file = new File(jarUrl);
			return URLDecoder.decode(file.getParent(), "UTF-8");
		} catch (Exception e) {

		}
		return null;
	}
}
